package com.example.mydemo.controller;

import com.example.mydemo.entity.Test;
import com.example.mydemo.response.Response;
import com.example.mydemo.dto.DTO;
import com.example.mydemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class TestController {

    @Autowired
    private StudentService studentservice;
    @GetMapping("/test/{id}")
    public Response<DTO> getStudentById(@PathVariable Integer id) {
        try {
            DTO dto = studentservice.getStudentById(id);
            return Response.newsuccess(dto);
        } catch (RuntimeException ex) {
            // 捕获异常并返回自定义错误响应
            return Response.newfail(ex.getMessage());
        }
    }
    @PostMapping("/test")
    public Response<DTO> createStudent(@RequestBody Test test) {
        List<Test> list = studentservice.findbyName(test.getName());
        System.out.println( list);
        if(!CollectionUtils.isEmpty(list)){
            return Response.newfail("该用户已存在");
        }
        try {
            DTO dto = studentservice.createStudent(test);
            return Response.newsuccess(dto);
        } catch (RuntimeException ex) {
            // 捕获异常并返回自定义错误响应
            return Response.newfail(ex.getMessage());
        }
    }
    @DeleteMapping("/test/{id}")
    public String deleteStudent(@PathVariable Integer id) {
        System.out.println( id);
        try {
            studentservice.deleteStudent(id);
            return "success";
        } catch (RuntimeException ex) {
            // 捕获异常并返回自定义错误响应
            return ex.getMessage();
        }
    }
    @PutMapping("/test/{id}")
    public Response<DTO> updateStudent(@PathVariable Integer id, @RequestBody Test test) {
        try {
            DTO dto = studentservice.updateStudent(id,test);
            return Response.newsuccess(dto);
        } catch (RuntimeException ex) {
            // 捕获异常并返回自定义错误响应
            return Response.newfail(ex.getMessage());
        }
    }

}
